package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.service.CourseBaseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {

    @Autowired
    CourseBaseMapper courseBaseMapper;

    @Autowired
    CourseMarketServiceImpl courseMarketService;

    @Autowired
    CourseCategoryMapper courseCategoryMapper;

    @Autowired
    TeachplanServiceImpl teachplanService;

    @Autowired
    CourseTeacherServiceImpl courseTeacherService;

    @Autowired
    DictionaryServiceImpl dictionaryService;

    @Override
    public PageResult<CourseBase> getCourseBaseListPage(PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        //构造分页查询器
        Page<CourseBase> courseBasePage = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());

        //构造查询条件
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();

        //构建查询条件，根据课程审核状态查询
        queryWrapper.eq(StringUtils.isNotBlank(queryCourseParamsDto.getAuditStatus()), CourseBase::getAuditStatus, queryCourseParamsDto.getAuditStatus());

        //构建查询条件，根据课程名称查询
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()), CourseBase::getName, queryCourseParamsDto.getCourseName());

        //构建查询条件，根据课程发布状态查询
        //todo:根据课程发布状态查询
        // 查询数据字典表课程状态码
//        Dictionary dictionary = dictionaryService.getOne(new LambdaQueryWrapper<Dictionary>().eq(Dictionary::getName, "课程发布状态"));
//        String itemValues = dictionary.getItemValues();
//        String[] split = itemValues.substring(1, itemValues.length() - 1).split(",");
//        System.out.println(itemValues);
//        System.out.println(split);

        // 设置条件


        // 查询结果
        Page<CourseBase> page = courseBaseMapper.selectPage(courseBasePage, queryWrapper);


        return new PageResult<CourseBase>(page.getRecords(), page.getTotal(), page.getPages(), page.getSize());
    }


    /**
     * 新增课程
     *
     * @param addCourseDto
     * @return CourseBaseInfoDto
     * @author hjh
     * @date 2023/5/5 16:37
     */

    @Override
    @Transactional
    public CourseBaseInfoDto CreateCourseBaseInfoDto(Long companyId, AddCourseDto addCourseDto) {
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(addCourseDto, courseBase);
        //设置审核状态
        courseBase.setAuditStatus("202002");
        //设置发布状态
        courseBase.setStatus("203001");
        // 添加时间
        courseBase.setCreateDate(LocalDateTime.now());
        //机构id
        courseBase.setCompanyId(companyId);
        int insert = courseBaseMapper.insert(courseBase);
        if (insert < 0) {
            XueChengPlusException.cast("添加课程信息失败！");
        }
        // 保存营销信息
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(addCourseDto, courseMarket);
        courseMarket.setId(courseBase.getId());
        CourseMarket byId = courseMarketService.getById(courseBase.getId());
        courseMarketService.saveOrUpdate(courseMarket);


        // 查询返回courseBaseInfo
        //根据课程id查询课程基本信息，包括基本信息和营销信息
        CourseBase courseBase1 = this.getById(courseBase.getId());
        if (courseBase1 == null) {
            return null;
        }
        CourseMarket courseMarket1 = courseMarketService.getById(courseBase.getId());


        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase1, courseBaseInfoDto);
        if(courseMarket1 != null){
            BeanUtils.copyProperties(courseMarket1, courseBaseInfoDto);
        }

        CourseCategory courseCategoryBySt = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategoryBySt.getName());
        CourseCategory courseCategoryByMt = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(courseCategoryByMt.getName());

        return courseBaseInfoDto;
    }

    /**
     * 修改课程信息
     * @author hjh
     * @date 2023/5/6 10:23
     * @param editCourseDto
     * @return CourseBaseInfoDto
     */

    @Override
    @Transactional
    public CourseBaseInfoDto modifyCourseBase(Long companyId,EditCourseDto editCourseDto) {
        if(editCourseDto.getId() == null){
            XueChengPlusException.cast("课程id不能为空");
        }
        CourseBase courseBase = courseBaseMapper.selectById(editCourseDto.getId());
        if( courseBase == null){
            XueChengPlusException.cast("课程不存在");
        }

        //校验本机构只能修改本机构的课程
        if(!courseBase.getCompanyId().equals(companyId)){
            XueChengPlusException.cast("本机构只能修改本机构的课程");
        }

//        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(editCourseDto,courseBase);
        int i = courseBaseMapper.updateById(courseBase);
        if(i<0){
            XueChengPlusException.cast("修改课程信息失败");
        }

        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(editCourseDto,courseMarket);
        boolean b = courseMarketService.updateById(courseMarket);
        return getCourseBaseInfo(editCourseDto.getId());
    }

    /**
     * 通过课程id查询课程信息
     * @author hjh
     * @date 2023/5/6 10:15
     * @param courseId
     * @return CourseBaseInfoDto
     */

    @Override
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId) {
        // 查询课程基本信息表
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null){
            XueChengPlusException.cast("未查询到课程信息");
        }
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);


        // 查询营销信息表
        CourseMarket courseMarket = courseMarketService.getById(courseId);
        if(courseMarket==null){
            XueChengPlusException.cast("未查询到课程营销信息");

        }
        BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);

        //查询分类名称
        CourseCategory courseCategoryBySt = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategoryBySt.getName());
        CourseCategory courseCategoryByMt = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(courseCategoryByMt.getName());

        return courseBaseInfoDto;
    }

    /**
     * 删除课程信息
     * @author hjh
     * @date 2023/5/7 19:42
     * @param courseId
     */

    @Override
    @Transactional
    public void deleteCourseBase(Long courseId) {
//        课程的审核状态为未提交时方可删除。
         CourseBase courseBase = this.getById(courseId);
         if(courseBase==null){
             XueChengPlusException.cast("课程未找到");
         }
         if(!courseBase.getStatus().equals("203001")){
             XueChengPlusException.cast("课程状态不为未提交不可删除");
         }
//        删除课程需要删除课程相关的基本信息、营销信息、课程计划、课程教师信息。
        this.removeById(courseId);
        courseMarketService.removeById(courseId);
        teachplanService.remove(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getCourseId, courseId));
        courseTeacherService.remove(new LambdaQueryWrapper<CourseTeacher>().eq(CourseTeacher::getCourseId, courseId));
    }


}
